package com.ljkj.lawyer.lawyer.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.ljkj.lawyer.lawyer.chainmaker.AddHashCodeByUserIdParam;
import com.ljkj.lawyer.lawyer.common.ContractConstant;
import com.ljkj.lawyer.lawyer.common.HashCodeTypeEnum;
import com.ljkj.lawyer.lawyer.common.MessageResult;
import com.ljkj.lawyer.lawyer.dao.LawyerCodeDao;
import com.ljkj.lawyer.lawyer.dao.LawyerDao;
import com.ljkj.lawyer.lawyer.entity.LawyerAddRecordEntity;
import com.ljkj.lawyer.lawyer.entity.LawyerEntity;
import com.ljkj.lawyer.lawyer.ipfs.AddResult;
import com.ljkj.lawyer.lawyer.ipfs.SelectResult;
import com.ljkj.lawyer.lawyer.param.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gaokecheng
 * @since 2021-11-02
 */
@Service
public class LawyerService {
    @Autowired
    private LawyerDao lawyerDao;
    @Autowired
    private LawyerCodeDao lawyerCodeDao;
    @Autowired
    private HttpService httpService;

    public MessageResult addLawyerInfo(AddParam addParam) {
        //更新所有member下简介为过去式
        lawyerDao.updateAllLawyerByMemberId(addParam.getMemberId());
        LawyerEntity lawyerEntity = new LawyerEntity();
        BeanUtils.copyProperties(addParam, lawyerEntity);
        lawyerEntity.setCreateTime(LocalDateTime.now());
        lawyerEntity.setIsLast(1);
        lawyerEntity.setUpdateTime(LocalDateTime.now());
        lawyerEntity = lawyerDao.save(lawyerEntity);//保存最新的
        //加入到ipfs
        String hash = this.addToIpfs(addParam, lawyerEntity.getMemberId());
        //链上上传
        AddHashCodeByUserIdParam addHashCodeByUserIdParam = new AddHashCodeByUserIdParam();
        addHashCodeByUserIdParam.setContractName(ContractConstant.LAWYER);
        //加入code类型
        addHashCodeByUserIdParam.setHashCode(getLawyerJson(hash));
        addHashCodeByUserIdParam.setUserId(addParam.getMemberId());
        //添加到长安链
        MessageResult messageResult = httpService.addHashCodeToChainmaker(addHashCodeByUserIdParam);
        //存储添加记录
        LawyerAddRecordEntity lawyerCodeRecordEntity = new LawyerAddRecordEntity();
        lawyerCodeRecordEntity.setHashCode(getLawyerJson(hash));
        lawyerCodeRecordEntity.setLawyerId(lawyerEntity.getId());
        lawyerCodeRecordEntity.setTxId(messageResult.getData().toString());
        lawyerCodeRecordEntity.setMemberId(addParam.getMemberId());
        lawyerCodeRecordEntity.setCreateTime(LocalDateTime.now());
        lawyerCodeRecordEntity.setUpdateTime(LocalDateTime.now());
        lawyerCodeDao.save(lawyerCodeRecordEntity);
        MessageResult result = MessageResult.success();
        result.setData(Boolean.TRUE);
        return result;
    }


    public MessageResult getLastLawyerInfoByMemberId(Integer memberId) {
        LawyerEntity lawyerEntity = lawyerDao.getLastLawyerInfoByMemberId(memberId);
        LawyerDetailRes lawyerDetailRes = new LawyerDetailRes();
        if(lawyerEntity != null){
            BeanUtils.copyProperties(lawyerEntity, lawyerDetailRes);
        }
        HttpMemberRes httpMemberRes = httpService.getMember(memberId);
        if (null != httpMemberRes) {
            lawyerDetailRes.setAvatar(httpMemberRes.getAvatar());
            lawyerDetailRes.setUsername(httpMemberRes.getUsername());
            lawyerDetailRes.setPhone(httpMemberRes.getMobilePhone());
        }
        MessageResult messageResult = MessageResult.success();
        messageResult.setData(lawyerDetailRes);
        return messageResult;
    }


    public MessageResult getDataByHashCode(String hashCode) {
        SelectResult selectResult = httpService.getString(hashCode);
        MessageResult messageResult = MessageResult.success();
        messageResult.setData(selectResult.getResult());
        return messageResult;
    }

    public MessageResult getHashCodeListByMemberId(Integer memberId, Integer pageNum, Integer pageSize) {
        List<HashCodeListParam> hashCodeListParamList = new ArrayList<>();
        HashCodeRes hashCodeRes = new HashCodeRes();
        hashCodeRes.setMemberId(memberId);
        HttpMemberRes httpMemberRes = httpService.getMember(memberId);
        if (null != httpMemberRes) {
            hashCodeRes.setAvatar(httpMemberRes.getAvatar());
            hashCodeRes.setUsername(httpMemberRes.getUsername());
        }
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        Page<LawyerAddRecordEntity> pageResult = lawyerCodeDao.getHashCodeListByMemberId(memberId, pageable);
        List<LawyerAddRecordEntity> lawyerAddRecordEntityList = pageResult.getContent();
        hashCodeRes.setPageNum(pageNum);
        hashCodeRes.setPageSize(pageSize);
        hashCodeRes.setTotal(pageResult.getTotalElements());
        hashCodeRes.setPages(pageResult.getTotalPages());
        if (!CollectionUtils.isEmpty(lawyerAddRecordEntityList)) {
            lawyerAddRecordEntityList.forEach(p -> {
                HashCodeListParam hashCodeListParam = new HashCodeListParam();
                hashCodeListParam.setHashCode(p.getHashCode());
                hashCodeListParam.setTxId(p.getTxId());
                hashCodeListParam.setUpdateTime(p.getCreateTime());
                hashCodeListParamList.add(hashCodeListParam);
            });
        }
        hashCodeRes.setHashCodeListParamList(hashCodeListParamList);
        MessageResult messageResult = MessageResult.success();
        messageResult.setData(hashCodeRes);
        return messageResult;
    }

    public String addToIpfs(AddParam addParam, Integer memberId) {
        IpfsParam ipfsParam = new IpfsParam();
        BeanUtils.copyProperties(addParam, ipfsParam);
        HttpMemberRes httpMemberRes = httpService.getMember(memberId);
        if (null != httpMemberRes) {
            ipfsParam.setAvatar(httpMemberRes.getAvatar());
            ipfsParam.setUsername(httpMemberRes.getUsername());
            ipfsParam.setPhone(httpMemberRes.getMobilePhone());
        }
        ipfsParam.setCreateTime(DateUtil.formatDateTime(new Date()));
        AddResult addResult = httpService.addString(JSON.toJSONString(ipfsParam));
        return addResult.getHash();
    }

    public MessageResult getLawyerHistoryByMemberId(Integer memberId, Integer pageNum, Integer pageSize) {
        List<LawyerHistoryListRes> lawyerHistoryListResList = new ArrayList<>();
        LawyerHistoryRes lawyerHistoryRes = new LawyerHistoryRes();
        lawyerHistoryRes.setMemberId(memberId);
        HttpMemberRes httpMemberRes = httpService.getMember(memberId);
        if (null != httpMemberRes) {
            lawyerHistoryRes.setAvatar(httpMemberRes.getAvatar());
            lawyerHistoryRes.setUsername(httpMemberRes.getUsername());
        }
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        Page<LawyerEntity> pageResult = lawyerDao.getLawyerHistoryByMemberId(memberId, pageable);
        List<LawyerEntity> lawyerEntityList = pageResult.getContent();
        lawyerHistoryRes.setPageNum(pageNum);
        lawyerHistoryRes.setPageSize(pageSize);
        lawyerHistoryRes.setTotal(pageResult.getTotalElements());
        lawyerHistoryRes.setPages(pageResult.getTotalPages());
        if (!CollectionUtils.isEmpty(lawyerEntityList)) {
            lawyerEntityList.stream().forEach(p -> {
                LawyerHistoryListRes lawyerHistoryListRes = new LawyerHistoryListRes();
                BeanUtils.copyProperties(p, lawyerHistoryListRes);
                lawyerHistoryListResList.add(lawyerHistoryListRes);
            });
        }
        lawyerHistoryRes.setLawyerHistoryListResList(lawyerHistoryListResList);
        MessageResult messageResult = MessageResult.success();
        messageResult.setData(lawyerHistoryRes);
        return messageResult;
    }

    public String getLawyerJson(String hashCode){
        JsonParam jsonParam = new JsonParam();
        jsonParam.setHashCode(hashCode);
        jsonParam.setCodeType(HashCodeTypeEnum.LAWYER_INFO.getCode());
        return JSON.toJSONString(jsonParam);
    }
}
